package com.yunhe.rentcars.pro.service.car.impl;



import com.yunhe.rentcars.commons.annoaction.Log;
import com.yunhe.rentcars.commons.constant.Constants;
import com.yunhe.rentcars.commons.dto.Pageable;
import com.yunhe.rentcars.pro.dao.car.CarMaintainDao;
import com.yunhe.rentcars.pro.dao.car.CarsDao;
import com.yunhe.rentcars.pro.entity.car.CarInsurance;
import com.yunhe.rentcars.pro.entity.car.CarMaintain;
import com.yunhe.rentcars.pro.entity.rent.Cars;
import com.yunhe.rentcars.pro.service.car.CarMaintainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author maliang
 * @version V1.0
 * @date 2017/11/23 0023 15:00
 * @Description: 车辆保养业务层
 */
@Service
public class CarMaintainServiceImpl implements CarMaintainService {

    @Autowired
    private CarMaintainDao carMaintainDao;
    @Autowired
    private CarsDao carsDao;

    @Override
    @Log(value = "添加车辆年检记录",type = 1)
    public void save(CarMaintain carMaintain) {
        carstate(carMaintain);
        carMaintainDao.save(carMaintain);
    }

    @Override
    @Log(value = "删除年检记录",type = 2)
    public void delBatch(String ids) {
        String[] split = ids.split(",");
        carMaintainDao.delBatch(split);
    }

    @Override
    @Log(value = "修改年检记录",type = 3)
    public void update(CarMaintain carMaintain) {
        carstate(carMaintain);
        carMaintainDao.update(carMaintain);
    }

    @Override
    public Pageable<CarMaintain> find(CarMaintain carMaintain, Integer offset, Integer limit) {
        Pageable<CarMaintain> pageable = new Pageable<>();
        Long count = carMaintainDao.findCount(carMaintain);
        List<CarMaintain> rows = null;
        if(count > 0){
            rows = carMaintainDao.findList(carMaintain.getCarCode(), carMaintain.getUsecarTime(), carMaintain.getReturnTime(), offset, limit);
        }
        pageable.setTotal(count.intValue());
        pageable.setRows(rows);
        return pageable;
    }

    @Override
    public CarMaintain findOne(Long recordId) {
        return carMaintainDao.findOne(recordId);
    }


    /**
     * 更改车辆状态
     * @param carMaintain
     */
    public void carstate(CarMaintain carMaintain){
        Date returnTime = carMaintain.getReturnTime();
        Cars cars = new Cars();
        cars.setCarcode(carMaintain.getCarCode());
        if(returnTime != null) {
            carMaintain.setStatus(Constants.CAR_NORMAL);
            cars.setMaintaintime(carMaintain.getUsecarTime()); // 保养时间
            cars.setNextmaintaintime(carMaintain.getNextTime()); // 下次保养时间
            cars.setMaintainmile(carMaintain.getNextMile()); // 下次保养里程
            cars.setCarstate(Constants.CAR_NORMAL);
        } else {
            cars.setCarstate(Constants.CAR_IN_MAINTAIN);  //车辆保养中
        }
        carsDao.carState(cars);
    }
}
